When working on some sites, you might want to hide or show content in your articles based on user meta.
This tutorial idea was given to me by a member of the Post Status club. You could refactor the shortcodes that we create here into one shortcode. I’ll leave that to you for practice.
So, how will this work? We will use the function get_user_meta
to get data from the User. Then, by using a shortcode, we will wrap the content that we want to show or hide.
We will use the following attributes for the shortcode:
userfield
– the meta key,value
– the value we will use to compare against the meta value,compare
– this will be =,>=,>,<= & < that will be use to define how we compare the values,format
– how we will format thevalue
,format_meta
– how we will format the value we get from meta.
Why are we using format
and format_meta
? Since we enter attributes in shortcode, they are usually a string (correct me if I’m wrong) so by using format
and format_meta
, we can decide that the correct type of values are compared.
Hiding the content
Since we are using the user meta data to hide the content, if the user is not logged-in, we can decide to hide it as well or show it. We will show the content if the user is not logged in.
Let’s now define the shortcode:
We use the variable $hide_content here and update it through the switch
using the value from compare
.
Showing the content
We will use the same approach here. You’ll notice the code is almost the same. Since we are trying to show some content here, we will hide it if the user is not logged in.
Toggling the content
So now, here is something to practice. Try to create a new shortcode that will toggle the content by action. If you put the action to show, show the content if it compares correctly. If you put the action to hide, then hide it if it compare correctly.
This part is available only to the members. If you want to become a member and support my work go to this link and subscribe: Become a Member
Conclusion
Shortcodes like this could be used for showing restricted content for only certain members of your site. Or you could use this when tagging users and storing that in the meta. You could then show different content by tags.
I would recommend, for further practice, to make it even more complex so you accept roles. Also, some meta data could be stored as an array, so how would you compare that?
Write your solution in the comment below!
Become a Sponsor
Share this: